#include <iostream>
#include "SymbolTablesManager.hpp"
#include "SymbolTable.hpp"

class SymbolTablesManager;


SymbolTablesManager::SymbolTablesManager() {
	this->tables = new std::vector<SymbolTable *>();
	this->currentTable = NULL;
}

SymbolTablesManager::~SymbolTablesManager() {
	for(unsigned int i=0;i<this->tables->size();i++){
		delete (*this->tables)[i];
		(*this->tables)[i] = NULL;
	}

	delete this->tables;
	this->currentTable = NULL;
}


/**
 * Si tout ce passe bien, la table "racine" sera la table du programme donc la première insérée
 */
SymbolTable * SymbolTablesManager::getRootTable() {
	if (!tables->empty()) {
		return (*tables)[0];
	} else {
		return NULL;
	}
}

SymbolTable * SymbolTablesManager::gotoRootTable() {
	if (!tables->empty()) {
		return currentTable = (*tables)[0];
	}
	return NULL;
}

void SymbolTablesManager::addRecordTable(SymbolTable * recTable){
	this->tables->push_back(recTable);
}

void SymbolTablesManager::push() {
	SymbolTable * temp = new SymbolTable(currentTable, currentTable);
	this->tables->push_back(temp);
	currentTable = temp;
}

void SymbolTablesManager::pushRecord() {
	SymbolTable * temp = new SymbolTable(currentTable, currentTable);
	this->tables->push_back(temp);
	currentTable = temp;
}


void SymbolTablesManager::pop() {
	if (currentTable != NULL) {
		SymbolTable * callingContext = currentTable->getCallingCont();
		if (callingContext != NULL) {
			currentTable = callingContext;
		} else {
			currentTable = NULL;
		}

	}
}

SymbolTable * SymbolTablesManager::getCurrent() {
	return currentTable;
}

void SymbolTablesManager::show() {
	for(unsigned int i=0;i<tables->size();i++){
		std::cout << std::endl;
		(*tables)[i]->show();
	}
}


/*
#include <iostream>
using namespace std;
void SymbolTablesManager::test() {

	SymbolTablesManager * manager = new SymbolTablesManager;
	cout << "Current table == NULL ? " << (manager->getCurrent() == NULL) << endl;
	cout << "Root table == NULL ? " << (manager->getRootTable() == NULL) << endl;

	for (int i = 0; i < 10; ++i) {
		int iParent = i-1;

		manager->push();
		cout << "Table " << i << " ajoutée : " << manager->getCurrent() << endl;
		cout << "\t(parent : " << iParent << " : " << manager->getCurrent()->getParent() << ")" << endl;
	}
	cout << "Root table : " << manager->getRootTable() << endl;
	for (int i = 9; i >= 0; --i) {
		cout << "Table courante qui va être enlevée : " << manager->getCurrent() << endl;
		manager->pop();
	}

	delete manager;
}

 * 
 */
